<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>分类: 技术教程 | 小小程序员</title><meta name="author" content="十一星野"><meta name="copyright" content="十一星野"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="MyBatis 是一款非常流行的 ORM 框架，相信很多小伙伴都在使用。我们经常会把它和 MyBatis-Plus 或者 MBG 一起使用，用多了之后对于其一些常规操作就不太熟悉了。最近总结了下 MyBatis 的实用用法和技巧，希望对大家有所帮助！  #MyBatis简介MyBatis是一款优秀的开源持久层框架，支持自定义SQL查询、存储过程和高级映射，目前在Github上已有17k+Star">
<meta property="og:type" content="article">
<meta property="og:title" content="MyBatis这样用，同事直呼哇塞，堪称最佳实践！">
<meta property="og:url" content="https://ko25891wan.gitlab.io/2024/01/a85ffb7760b7.html">
<meta property="og:site_name" content="小小程序员">
<meta property="og:description" content="MyBatis 是一款非常流行的 ORM 框架，相信很多小伙伴都在使用。我们经常会把它和 MyBatis-Plus 或者 MBG 一起使用，用多了之后对于其一些常规操作就不太熟悉了。最近总结了下 MyBatis 的实用用法和技巧，希望对大家有所帮助！  #MyBatis简介MyBatis是一款优秀的开源持久层框架，支持自定义SQL查询、存储过程和高级映射，目前在Github上已有17k+Star">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png">
<meta property="article:published_time" content="2024-01-21T09:29:26.000Z">
<meta property="article:modified_time" content="2024-02-02T14:47:57.690Z">
<meta property="article:author" content="十一星野">
<meta property="article:tag" content="宅男,热血">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ko25891wan.gitlab.io/2024/01/a85ffb7760b7.html"><link rel="preconnect" href="//fastly.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.staticfile.org/egjs-infinitegrid/4.11.0/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '分类: 技术教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-02-02 22:47:57'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="小小程序员"><span class="site-name">小小程序员</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">MyBatis这样用，同事直呼哇塞，堪称最佳实践！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-21T09:29:26.000Z" title="发表于 2024-01-21 17:29:26">2024-01-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-02-02T14:47:57.690Z" title="更新于 2024-02-02 22:47:57">2024-02-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/">技术教程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/">mall</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/%E5%8F%82%E8%80%83%E7%AF%87/">参考篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="MyBatis这样用，同事直呼哇塞，堪称最佳实践！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>MyBatis 是一款非常流行的 ORM 框架，相信很多小伙伴都在使用。我们经常会把它和 MyBatis-Plus 或者 MBG 一起使用，用多了之后对于其一些常规操作就不太熟悉了。最近总结了下 MyBatis 的实用用法和技巧，希望对大家有所帮助！</p>
</blockquote>
<h2 id="MyBatis简介"><a href="#MyBatis简介" class="headerlink" title="#MyBatis简介"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#mybatis%E7%AE%80%E4%BB%8B">#</a>MyBatis简介</h2><p>MyBatis是一款优秀的开源持久层框架，支持自定义SQL查询、存储过程和高级映射，目前在Github上已有<code>17k+Star</code>。在MyBatis中，我们可以在XML中编写SQL语句，然后绑定到Java方法中，通过参数和结果集的自动映射来实现复杂的查询逻辑。MyBatis消除了几乎所有JDBC操作和手动绑定参数操作，使用起来非常方便！</p>
<h2 id="在SpringBoot中集成"><a href="#在SpringBoot中集成" class="headerlink" title="#在SpringBoot中集成"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E5%9C%A8springboot%E4%B8%AD%E9%9B%86%E6%88%90">#</a>在SpringBoot中集成</h2><blockquote>
<p>下面我们来聊聊MyBatis在SpringBoot中的使用，首先我们需要集成它。</p>
</blockquote>
<ul>
<li>在<code>pom.xml</code>中添加MyBatis提供的Spring Boot Starter；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;2.2.2&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在<code>application.yml</code>中配置好编写SQL实现的<code>xml</code>文件路径，这里我们存放在<code>resources/dao</code>目录下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mybatis:</span><br><span class="line">  mapper-locations:</span><br><span class="line">    - classpath:dao/*.xml</span><br></pre></td></tr></table></figure>

<ul>
<li>然后添加Java配置，通过<code>@MapperScan</code>配置好Dao接口路径，这样就可以开始使用了。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * MyBatis配置类</span><br><span class="line"> * Created by macro on 2019/4/8.</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">@MapperScan(&quot;com.macro.mall.tiny.dao&quot;)</span><br><span class="line">public class MyBatisConfig &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="基本使用"><a href="#基本使用" class="headerlink" title="#基本使用"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8">#</a>基本使用</h2><blockquote>
<p>下面我们来聊聊MyBatis的基本使用方法，涵盖了基本的增删改查操作。</p>
</blockquote>
<h3 id="表结构说明"><a href="#表结构说明" class="headerlink" title="#表结构说明"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E8%A1%A8%E7%BB%93%E6%9E%84%E8%AF%B4%E6%98%8E">#</a>表结构说明</h3><p>这里将以mall项目中权限管理模块相关表为例进行介绍，具体表结构如下。</p>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:47:52_mybatis_start_01-f5eae6f7.png"></p>
<h3 id="项目结构说明"><a href="#项目结构说明" class="headerlink" title="#项目结构说明"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84%E8%AF%B4%E6%98%8E">#</a>项目结构说明</h3><p>本文示例使用了<code>mall-learning</code>项目中的<code>mall-tiny-mybatis</code>模块代码，具体项目结构如下。</p>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:47:52_mybatis_start_02-1dbe9944.png"></p>
<h3 id="select"><a href="#select" class="headerlink" title="#select"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#select">#</a>select</h3><ul>
<li>首先是查询操作，这里我们以后台用户表<code>ums_admin</code>为例，编写一个<code>根据ID查询用户</code>的方法，先创建实体类<code>UmsAdmin</code>；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">public class UmsAdmin implements Serializable &#123;</span><br><span class="line">    private Long id;</span><br><span class="line"></span><br><span class="line">    private String username;</span><br><span class="line"></span><br><span class="line">    private String password;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;头像&quot;)</span><br><span class="line">    private String icon;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;邮箱&quot;)</span><br><span class="line">    private String email;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;昵称&quot;)</span><br><span class="line">    private String nickName;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;备注信息&quot;)</span><br><span class="line">    private String note;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;创建时间&quot;)</span><br><span class="line">    private Date createTime;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;最后登录时间&quot;)</span><br><span class="line">    private Date loginTime;</span><br><span class="line"></span><br><span class="line">    @ApiModelProperty(value = &quot;帐号启用状态：0-&gt;禁用；1-&gt;启用&quot;)</span><br><span class="line">    private Integer status;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后创建数据操作的接口<code>UmsAdminDao</code>，再添加对应的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 根据ID查询用户</span><br><span class="line">     */</span><br><span class="line">    UmsAdmin selectByIdSimple(Long id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>再创建<code>xml</code>文件<code>UmsAdminDao.xml</code>，添加查询方法的SQL实现；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectByIdSimple&quot; resultType=&quot;com.macro.mall.tiny.model.UmsAdmin&quot;&gt;</span><br><span class="line">    select * from ums_admin where id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后编写测试类，注入Dao，调用Dao方法来进行测试；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * MyBatis基本操作测试</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@SpringBootTest</span><br><span class="line">public class MyBatisBaseTest &#123;</span><br><span class="line"></span><br><span class="line">    private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisBaseTest.class);</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsAdminDao umsAdminDao;</span><br><span class="line"></span><br><span class="line">    @Test</span><br><span class="line">    void testSelectByIdSimple()&#123;</span><br><span class="line">        UmsAdmin umsAdmin = umsAdminDao.selectByIdSimple(1L);</span><br><span class="line">        LOGGER.info(&quot;testSelectByIdSimple result=&#123;&#125;&quot;,umsAdmin);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>此时你会发现，对于一些数据库表中以<code>下划线</code>分割的返回字段无法自动映射，可以通过对字段取别名的方式来进行映射；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectById&quot; resultType=&quot;com.macro.mall.tiny.model.UmsAdmin&quot;&gt;</span><br><span class="line">    select username,</span><br><span class="line">           password,</span><br><span class="line">           icon,</span><br><span class="line">           email,</span><br><span class="line">           nick_name   as nickName,</span><br><span class="line">           note,</span><br><span class="line">           create_time as createTime,</span><br><span class="line">           login_time  as loginTime,</span><br><span class="line">           status</span><br><span class="line">    from ums_admin</span><br><span class="line">    where id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果你觉得这种方式比较麻烦，也可以通过在<code>application.yml</code>中开启全局下划线自动转驼峰功能来解决，个人习惯使用第一种。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mybatis:</span><br><span class="line">  configuration:</span><br><span class="line">    # 下划线自动转驼峰</span><br><span class="line">    map-underscore-to-camel-case: true</span><br></pre></td></tr></table></figure>

<h3 id="insert"><a href="#insert" class="headerlink" title="#insert"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#insert">#</a>insert</h3><ul>
<li>接下来我们来编写一个<code>插入单个用户</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 插入用户</span><br><span class="line">     */</span><br><span class="line">    int insert(UmsAdmin entity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在xml中编写对应的SQL实现，这里需要注意的是如果想返回插入后的自增ID的话，需要使用<code>selectKey</code>标签进行配置。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;insert id=&quot;insert&quot;&gt;</span><br><span class="line">    insert into ums_admin(username, password, icon, email, nick_name, note, create_time, login_time)</span><br><span class="line">    values (#&#123;username&#125;, #&#123;password&#125;, #&#123;icon&#125;, #&#123;email&#125;, #&#123;nickName&#125;, #&#123;note&#125;, #&#123;createTime&#125;, #&#123;loginTime&#125;)</span><br><span class="line">    &lt;selectKey keyColumn=&quot;id&quot; resultType=&quot;long&quot; keyProperty=&quot;id&quot; order=&quot;AFTER&quot;&gt;</span><br><span class="line">        SELECT LAST_INSERT_ID()</span><br><span class="line">    &lt;/selectKey&gt;</span><br><span class="line">&lt;/insert&gt;</span><br></pre></td></tr></table></figure>

<h3 id="update"><a href="#update" class="headerlink" title="#update"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#update">#</a>update</h3><ul>
<li>接下来我们来编写一个<code>根据ID修改用户信息</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 根据ID修改用户信息</span><br><span class="line">     */</span><br><span class="line">    int updateById(UmsAdmin entity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在xml中编写对应的SQL实现。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;update id=&quot;updateById&quot;&gt;</span><br><span class="line">    update ums_admin</span><br><span class="line">    set username = #&#123;username&#125;,</span><br><span class="line">        password = #&#123;password&#125;,</span><br><span class="line">        icon = #&#123;icon&#125;,</span><br><span class="line">        email = #&#123;email&#125;,</span><br><span class="line">        nick_name = #&#123;nickName&#125;,</span><br><span class="line">        note = #&#123;note&#125;,</span><br><span class="line">        create_time = #&#123;createTime&#125;,</span><br><span class="line">        login_time = #&#123;loginTime&#125;</span><br><span class="line">    where id = #&#123;id&#125;</span><br><span class="line">&lt;/update&gt;</span><br></pre></td></tr></table></figure>

<h3 id="delete"><a href="#delete" class="headerlink" title="#delete"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#delete">#</a>delete</h3><ul>
<li>接下来我们来编写一个<code>根据ID删除用户</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 根据ID删除用户</span><br><span class="line">     */</span><br><span class="line">    int deleteById(Long id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在xml中编写对应的SQL实现。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;delete id=&quot;deleteById&quot;&gt;</span><br><span class="line">    delete from  ums_admin where id = #&#123;id&#125;</span><br><span class="line">&lt;/delete&gt;</span><br></pre></td></tr></table></figure>

<h2 id="动态SQL"><a href="#动态SQL" class="headerlink" title="#动态SQL"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E5%8A%A8%E6%80%81sql">#</a>动态SQL</h2><blockquote>
<p>通过MyBatis的动态SQL功能，我们可以灵活地在xml中实现各种复杂的操作，动态SQL功能需要依赖MyBatis的各种标签，下面我们就来学习下。</p>
</blockquote>
<h3 id="if"><a href="#if" class="headerlink" title="#if"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#if">#</a>if</h3><ul>
<li><code>if</code>标签可以实现判断逻辑，这里我们以<code>根据用户名和Email模糊查询用户</code>为例，来聊聊它的使用；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 根据用户名和Email模糊查询用户</span><br><span class="line">     * 不输入查询所有</span><br><span class="line">     */</span><br><span class="line">    List&lt;UmsAdmin&gt; selectByUsernameAndEmailLike(@Param(&quot;username&quot;) String username, @Param(&quot;email&quot;) String email);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>xml中添加对应的SQL实现如下。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectByUsernameAndEmailLike&quot; resultType=&quot;com.macro.mall.tiny.model.UmsAdmin&quot;&gt;</span><br><span class="line">    select username,</span><br><span class="line">           password,</span><br><span class="line">           icon,</span><br><span class="line">           email,</span><br><span class="line">           nick_name   as nickName,</span><br><span class="line">           note,</span><br><span class="line">           create_time as createTime,</span><br><span class="line">           login_time  as loginTime,</span><br><span class="line">           status</span><br><span class="line">    from ums_admin</span><br><span class="line">    where 1=1</span><br><span class="line">    &lt;if test=&quot;username!=null and username!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">        and username like concat(&#x27;%&#x27;,#&#123;username&#125;,&#x27;%&#x27;)</span><br><span class="line">    &lt;/if&gt;</span><br><span class="line">    &lt;if test=&quot;email!=null and email!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">        and email like concat(&#x27;%&#x27;,#&#123;email&#125;,&#x27;%&#x27;)</span><br><span class="line">    &lt;/if&gt;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="choose"><a href="#choose" class="headerlink" title="#choose"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#choose">#</a>choose</h3><ul>
<li><code>choose</code>标签也可以实现判断逻辑，上面的例子中当我们不输入用户名和Email时，会查询出全部用户，我们如果想不查询出用户，可以使用它；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectByUsernameAndEmailLike2&quot; resultType=&quot;com.macro.mall.tiny.model.UmsAdmin&quot;&gt;</span><br><span class="line">    select username,</span><br><span class="line">    password,</span><br><span class="line">    icon,</span><br><span class="line">    email,</span><br><span class="line">    nick_name as nickName,</span><br><span class="line">    note,</span><br><span class="line">    create_time as createTime,</span><br><span class="line">    login_time as loginTime,</span><br><span class="line">    status</span><br><span class="line">    from ums_admin</span><br><span class="line">    where 1=1</span><br><span class="line">    &lt;choose&gt;</span><br><span class="line">        &lt;when test=&quot;username!=null and username!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            and username like concat(&#x27;%&#x27;,#&#123;username&#125;,&#x27;%&#x27;)</span><br><span class="line">        &lt;/when&gt;</span><br><span class="line">        &lt;when test=&quot;email!=null and email!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            and email like concat(&#x27;%&#x27;,#&#123;email&#125;,&#x27;%&#x27;)</span><br><span class="line">        &lt;/when&gt;</span><br><span class="line">        &lt;otherwise&gt;</span><br><span class="line">            and 1=2</span><br><span class="line">        &lt;/otherwise&gt;</span><br><span class="line">    &lt;/choose&gt;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="where"><a href="#where" class="headerlink" title="#where"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#where">#</a>where</h3><ul>
<li>上面的例子中我们为了SQL拼接不出错，添加了<code>where 1=1</code>这样的语句，其实可以使用<code>where</code>标签来实现查询条件，当标签内没有内容时会自动去除<code>where</code>关键字，同时还会去除开头多余的<code>and</code>关键字。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectByUsernameAndEmailLike3&quot; resultType=&quot;com.macro.mall.tiny.model.UmsAdmin&quot;&gt;</span><br><span class="line">    select username,</span><br><span class="line">    password,</span><br><span class="line">    icon,</span><br><span class="line">    email,</span><br><span class="line">    nick_name as nickName,</span><br><span class="line">    note,</span><br><span class="line">    create_time as createTime,</span><br><span class="line">    login_time as loginTime,</span><br><span class="line">    status</span><br><span class="line">    from ums_admin</span><br><span class="line">    &lt;where&gt;</span><br><span class="line">        &lt;if test=&quot;username!=null and username!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            and username like concat(&#x27;%&#x27;,#&#123;username&#125;,&#x27;%&#x27;)</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;email!=null and email!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            and email like concat(&#x27;%&#x27;,#&#123;email&#125;,&#x27;%&#x27;)</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">    &lt;/where&gt;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="set"><a href="#set" class="headerlink" title="#set"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#set">#</a>set</h3><ul>
<li>当我们拼接更新字段的语句时，也会面临同样的问题，此时可以使用<code>set</code>标签来解决，比如我们现在想写一个<code>根据ID选择性修改用户信息</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 根据ID选择性修改用户信息</span><br><span class="line">     */</span><br><span class="line">    int updateByIdSelective(UmsAdmin entity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>方法对应的SQL实现如下，这里既避免了使用<code>set</code>关键字，也会将多余的逗号去除。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;update id=&quot;updateByIdSelective&quot;&gt;</span><br><span class="line">    update ums_admin</span><br><span class="line">    &lt;set&gt;</span><br><span class="line">        &lt;if test=&quot;username!=null and username!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            username = #&#123;username&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;password!=null and password!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            password = #&#123;password&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;icon!=null and icon!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            icon = #&#123;icon&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;email!=null and email!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            email = #&#123;email&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;nickName!=null and nickName!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            nick_name = #&#123;nickName&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;note!=null and note!=&#x27;&#x27;&quot;&gt;</span><br><span class="line">            note = #&#123;note&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;createTime!=null&quot;&gt;</span><br><span class="line">            create_time = #&#123;createTime&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">        &lt;if test=&quot;loginTime!=null&quot;&gt;</span><br><span class="line">            login_time = #&#123;loginTime&#125;,</span><br><span class="line">        &lt;/if&gt;</span><br><span class="line">    &lt;/set&gt;</span><br><span class="line">    where id = #&#123;id&#125;</span><br><span class="line">&lt;/update&gt;</span><br></pre></td></tr></table></figure>

<h3 id="foreach"><a href="#foreach" class="headerlink" title="#foreach"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#foreach">#</a>foreach</h3><ul>
<li>通过<code>foreach</code>我们可以实现一些循环拼接SQL的逻辑，例如我们现在需要编写一个<code>批量插入用户</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 批量插入用户</span><br><span class="line">     */</span><br><span class="line">    int insertBatch(@Param(&quot;entityList&quot;) List&lt;UmsAdmin&gt; adminList);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>在xml中的对应SQL实现如下，在<code>foreach</code>标签中的内容会根据传入的集合参数进行循环拼接；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;insert id=&quot;insertBatch&quot;&gt;</span><br><span class="line">    insert into ums_admin(username, password, icon, email, nick_name, note, create_time, login_time) values</span><br><span class="line">    &lt;foreach collection=&quot;entityList&quot; separator=&quot;,&quot; item=&quot;item&quot;&gt;</span><br><span class="line">        (#&#123;item.username&#125;, #&#123;item.password&#125;, #&#123;item.icon&#125;, #&#123;item.email&#125;, #&#123;item.nickName&#125;, #&#123;item.note&#125;, #&#123;item.createTime&#125;, #&#123;item.loginTime&#125;)</span><br><span class="line">    &lt;/foreach&gt;</span><br><span class="line">&lt;/insert&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>再例如我们现在需要编写一个<code>根据用户ID批量查询</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsAdmin表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 根据用户ID批量查询</span><br><span class="line">     */</span><br><span class="line">    List&lt;UmsAdmin&gt; selectByIds(@Param(&quot;ids&quot;) List&lt;Long&gt; ids);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>在xml中的对应SQL实现如下，我们可以使用<code>open</code>、<code>close</code>属性指定拼接语句的前后缀。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectByIds&quot; resultType=&quot;com.macro.mall.tiny.model.UmsAdmin&quot;&gt;</span><br><span class="line">    select username,</span><br><span class="line">           password,</span><br><span class="line">           icon,</span><br><span class="line">           email,</span><br><span class="line">           nick_name   as nickName,</span><br><span class="line">           note,</span><br><span class="line">           create_time as createTime,</span><br><span class="line">           login_time  as loginTime,</span><br><span class="line">           status</span><br><span class="line">    from ums_admin</span><br><span class="line">    where id in</span><br><span class="line">    &lt;foreach collection=&quot;ids&quot; item=&quot;item&quot; open=&quot;(&quot; close=&quot;)&quot; separator=&quot;,&quot;&gt;</span><br><span class="line">        #&#123;item&#125;</span><br><span class="line">    &lt;/foreach&gt;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h2 id="高级查询"><a href="#高级查询" class="headerlink" title="#高级查询"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E9%AB%98%E7%BA%A7%E6%9F%A5%E8%AF%A2">#</a>高级查询</h2><blockquote>
<p>介绍完MyBatis的基本操作后，我们再来介绍下MyBatis的高级查询功能。</p>
</blockquote>
<h3 id="一对一映射"><a href="#一对一映射" class="headerlink" title="#一对一映射"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E4%B8%80%E5%AF%B9%E4%B8%80%E6%98%A0%E5%B0%84">#</a>一对一映射</h3><ul>
<li>在我们平时进行SQL查询时，往往会有<code>一对一</code>的情况，比如说我们这里有资源分类<code>ums_resource_category</code>和资源<code>ums_resource</code>两张表，资源和分类就是一对一的关系，如果你不想改动原实体类的话，可以编写一个扩展类继承<code>UmsResource</code>，并包含<code>UmsResourceCategory</code>属性；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * UmsResource扩展类</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Data</span><br><span class="line">public class UmsResourceExt extends UmsResource &#123;</span><br><span class="line"></span><br><span class="line">    private UmsResourceCategory category;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>例如我们需要编写一个<code>根据资源ID获取资源及分类信息</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsResource表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsResourceDao &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 根据资源ID获取资源及分类信息</span><br><span class="line">     */</span><br><span class="line">    UmsResourceExt selectResourceWithCategory(Long id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>在xml中的具体SQL实现如下，我们可以通过给<code>ums_resource_category</code>表中字段取以<code>category.xxx</code>的别名来自动进行自动映射；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectResourceWithCategory&quot; resultType=&quot;com.macro.mall.tiny.domain.UmsResourceExt&quot;&gt;</span><br><span class="line">    select ur.id,</span><br><span class="line">           ur.create_time  as createTime,</span><br><span class="line">           ur.name,</span><br><span class="line">           ur.url,</span><br><span class="line">           ur.description,</span><br><span class="line">           ur.category_id  as categoryId,</span><br><span class="line">           urc.id          as &quot;category.id&quot;,</span><br><span class="line">           urc.name        as &quot;category.name&quot;,</span><br><span class="line">           urc.sort        as &quot;category.sort&quot;,</span><br><span class="line">           urc.create_time as &quot;category.createTime&quot;</span><br><span class="line">    from ums_resource ur</span><br><span class="line">             left join ums_resource_category urc on ur.category_id = urc.id</span><br><span class="line">    where ur.id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>当然除了这种方式以外，我们还可以通过<code>ResultMap</code>+<code>association</code>标签来实现，不过在此之前我们在编写xml文件的时候，一般习惯于先给当前文件写一个<code>BaseResultMap</code>，用于对当前表的字段和对象属性进行直接映射，例如在<code>UmsResourceCategoryDao.xml</code>中这样实现；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;com.macro.mall.tiny.dao.UmsResourceCategoryDao&quot;&gt;</span><br><span class="line"></span><br><span class="line">    &lt;resultMap id=&quot;BaseResultMap&quot; type=&quot;com.macro.mall.tiny.model.UmsResourceCategory&quot;&gt;</span><br><span class="line">        &lt;id property=&quot;id&quot; column=&quot;id&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;createTime&quot; column=&quot;create_time&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;name&quot; column=&quot;name&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;sort&quot; column=&quot;sort&quot;/&gt;</span><br><span class="line">    &lt;/resultMap&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>在<code>UmsResourceDao.xml</code>中我们可以这样实现；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;com.macro.mall.tiny.dao.UmsResourceDao&quot;&gt;</span><br><span class="line"></span><br><span class="line">    &lt;resultMap id=&quot;BaseResultMap&quot; type=&quot;com.macro.mall.tiny.model.UmsResource&quot;&gt;</span><br><span class="line">        &lt;id property=&quot;id&quot; column=&quot;id&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;createTime&quot; column=&quot;create_time&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;name&quot; column=&quot;name&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;url&quot; column=&quot;url&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;description&quot; column=&quot;description&quot;/&gt;</span><br><span class="line">        &lt;result property=&quot;categoryId&quot; column=&quot;category_id&quot;/&gt;</span><br><span class="line">    &lt;/resultMap&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>编写完成后，我们的一对一<code>ResultMap</code>实现就很简单了，我们可以使用<code>association</code>标签进行一对一管理，配置<code>columnPrefix</code>属性将匹配到的字段直接映射到关联对象中去；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;resultMap id=&quot;ResourceWithCategoryMap&quot; type=&quot;com.macro.mall.tiny.domain.UmsResourceExt&quot; extends=&quot;BaseResultMap&quot;&gt;</span><br><span class="line">    &lt;association property=&quot;category&quot; resultMap=&quot;com.macro.mall.tiny.dao.UmsResourceCategoryDao.BaseResultMap&quot; columnPrefix=&quot;category_&quot;/&gt;</span><br><span class="line">&lt;/resultMap&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后再编写下Dao中方法对应SQL实现即可，这里直接使用上面的ResultMap，同时给<code>ums_resource_category</code>表中的字段指定了<code>category_</code>前缀以便于映射。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectResourceWithCategory2&quot; resultMap=&quot;ResourceWithCategoryMap&quot;&gt;</span><br><span class="line">    select ur.id,</span><br><span class="line">           ur.create_time,</span><br><span class="line">           ur.name,</span><br><span class="line">           ur.url,</span><br><span class="line">           ur.description,</span><br><span class="line">           ur.category_id,</span><br><span class="line">           urc.id          as category_id,</span><br><span class="line">           urc.name        as category_name,</span><br><span class="line">           urc.sort        as category_sort,</span><br><span class="line">           urc.create_time as category_create_time</span><br><span class="line">    from ums_resource ur</span><br><span class="line">             left join ums_resource_category urc on ur.category_id = urc.id</span><br><span class="line">    where ur.id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="一对多映射"><a href="#一对多映射" class="headerlink" title="#一对多映射"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%98%A0%E5%B0%84">#</a>一对多映射</h3><ul>
<li>在编写SQL查询时，一对多的情况也比较常见，例如这里的分类和资源就是一对多的情况；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * UmsResourceCategory扩展类</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Data</span><br><span class="line">public class UmsResourceCategoryExt extends UmsResourceCategory &#123;</span><br><span class="line"></span><br><span class="line">    private List&lt;UmsResource&gt; resourceList;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>例如我们现在需要编写一个<code>根据分类ID获取分类及对应资源</code>的方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义UmsResourceCategory表查询</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Repository</span><br><span class="line">public interface UmsResourceCategoryDao &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 根据分类ID获取分类及对应资源</span><br><span class="line">     */</span><br><span class="line">    UmsResourceCategoryExt selectCategoryWithResource(Long id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>在实现具体SQL前，我们需要先在xml中配置一个ResultMap，通过<code>collection</code>标签建立一对多关系；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;resultMap id=&quot;selectCategoryWithResourceMap&quot; type=&quot;com.macro.mall.tiny.domain.UmsResourceCategoryExt&quot; extends=&quot;BaseResultMap&quot;&gt;</span><br><span class="line">    &lt;collection property=&quot;resourceList&quot; columnPrefix=&quot;resource_&quot; resultMap=&quot;com.macro.mall.tiny.dao.UmsResourceDao.BaseResultMap&quot;/&gt;</span><br><span class="line">&lt;/resultMap&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在xml中编写具体的SQL实现，使用该ResultMap。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectCategoryWithResource&quot; resultMap=&quot;selectCategoryWithResourceMap&quot;&gt;</span><br><span class="line">    select urc.id,</span><br><span class="line">           urc.create_time,</span><br><span class="line">           urc.name,</span><br><span class="line">           urc.sort,</span><br><span class="line">           ur.id resource_id,</span><br><span class="line">           ur.create_time resource_create_time,</span><br><span class="line">           ur.name resource_name,</span><br><span class="line">           ur.url resource_url,</span><br><span class="line">           ur.description resource_description,</span><br><span class="line">           ur.category_id resource_category_id</span><br><span class="line">    from ums_resource_category urc</span><br><span class="line">    left join ums_resource ur on urc.id = ur.category_id</span><br><span class="line">    where urc.id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="分页插件"><a href="#分页插件" class="headerlink" title="#分页插件"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6">#</a>分页插件</h3><ul>
<li>我们平时实现查询逻辑时，往往还会遇到分页查询的需求，直接使用开源的<code>PageHelper</code>插件即可，首先在<code>pom.xml</code>中添加它的Starter；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--MyBatis分页插件--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;pagehelper-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.4.2&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在查询方法之前使用它的<code>startPage</code>方法传入分页参数即可，分页后的得到的数据可以在<code>PageInfo</code>中获取到。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * UmsResource的Service接口实现类</span><br><span class="line"> * Created by macro on 2022/10/20.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UmsResourceServiceImpl implements UmsResourceService &#123;</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsResourceDao umsResourceDao;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public PageInfo&lt;UmsResource&gt; page(Integer pageNum, Integer pageSize,Long categoryId) &#123;</span><br><span class="line">        PageHelper.startPage(pageNum,pageSize);</span><br><span class="line">        List&lt;UmsResource&gt; resourceList = umsResourceDao.selectListByCategoryId(categoryId);</span><br><span class="line">        PageInfo&lt;UmsResource&gt; pageInfo = new PageInfo&lt;&gt;(resourceList);</span><br><span class="line">        return pageInfo;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="总结"><a href="#总结" class="headerlink" title="#总结"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E6%80%BB%E7%BB%93">#</a>总结</h2><p>本文主要介绍了MyBatis中一些比较常规的用法，涵盖了SpringBoot集成、基本查询、动态SQL和高级查询，建议大家收藏起来，在对MyBatis的用法有所遗忘的时候拿出来看看。</p>
<h2 id="项目源码地址"><a href="#项目源码地址" class="headerlink" title="#项目源码地址"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_start.html#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80">#</a>项目源码地址</h2><p><a target="_blank" rel="noopener" href="https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-mybatis">https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-mybatis</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io">十一星野</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io/2024/01/a85ffb7760b7.html">https://ko25891wan.gitlab.io/2024/01/a85ffb7760b7.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ko25891wan.gitlab.io" target="_blank">小小程序员</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/01/3796ef2b2e7e.html" title="Nginx的这些妙用，你肯定有不知道的！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Nginx的这些妙用，你肯定有不知道的！</div></div></a></div><div class="next-post pull-right"><a href="/2024/01/81ea40d881c9.html" title="MongoDB快速入门，掌握这些刚刚好！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MongoDB快速入门，掌握这些刚刚好！</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">十一星野</div><div class="author-info__description">归途也还可爱</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Gitlab"><i class="fab fa-gitlab" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:ko25891wan@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatis%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">MyBatis简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9C%A8SpringBoot%E4%B8%AD%E9%9B%86%E6%88%90"><span class="toc-number">2.</span> <span class="toc-text">在SpringBoot中集成</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">基本使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A8%E7%BB%93%E6%9E%84%E8%AF%B4%E6%98%8E"><span class="toc-number">3.1.</span> <span class="toc-text">表结构说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84%E8%AF%B4%E6%98%8E"><span class="toc-number">3.2.</span> <span class="toc-text">项目结构说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#select"><span class="toc-number">3.3.</span> <span class="toc-text">select</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#insert"><span class="toc-number">3.4.</span> <span class="toc-text">insert</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#update"><span class="toc-number">3.5.</span> <span class="toc-text">update</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#delete"><span class="toc-number">3.6.</span> <span class="toc-text">delete</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8A%A8%E6%80%81SQL"><span class="toc-number">4.</span> <span class="toc-text">动态SQL</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if"><span class="toc-number">4.1.</span> <span class="toc-text">if</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#choose"><span class="toc-number">4.2.</span> <span class="toc-text">choose</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#where"><span class="toc-number">4.3.</span> <span class="toc-text">where</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#set"><span class="toc-number">4.4.</span> <span class="toc-text">set</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#foreach"><span class="toc-number">4.5.</span> <span class="toc-text">foreach</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%AB%98%E7%BA%A7%E6%9F%A5%E8%AF%A2"><span class="toc-number">5.</span> <span class="toc-text">高级查询</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E5%AF%B9%E4%B8%80%E6%98%A0%E5%B0%84"><span class="toc-number">5.1.</span> <span class="toc-text">一对一映射</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%98%A0%E5%B0%84"><span class="toc-number">5.2.</span> <span class="toc-text">一对多映射</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6"><span class="toc-number">5.3.</span> <span class="toc-text">分页插件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80"><span class="toc-number">7.</span> <span class="toc-text">项目源码地址</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/c60470b9a892.html" title="Java集合使用注意事项总结">Java集合使用注意事项总结</a><time datetime="2024-02-03T04:58:22.000Z" title="发表于 2024-02-03 12:58:22">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/81fb7a201f29.html" title="无题">无题</a><time datetime="2024-02-03T03:15:31.812Z" title="发表于 2024-02-03 11:15:31">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/5737c1ec69a9.html" title="Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)">Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)</a><time datetime="2024-01-31T06:56:16.000Z" title="发表于 2024-01-31 14:56:16">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/f510db7d2f19.html" title="Spring常见面试题总结">Spring常见面试题总结</a><time datetime="2024-01-31T06:55:58.000Z" title="发表于 2024-01-31 14:55:58">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/9be065e9f288.html" title="redis 面试">redis 面试</a><time datetime="2024-01-31T06:55:55.000Z" title="发表于 2024-01-31 14:55:55">2024-01-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By 十一星野</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.2.0/instantpage.min.js" type="module"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>